<template>
  <div class="app">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="line-height: 36px;">应用管理</span>
        <el-button style="float: right;" type="primary" @click="dialogOpen('add')" v-if="USER.auth.indexOf('addApp')!==-1">新增应用</el-button>
      </div>
      <s-table :table="table" @http="tableWatch">
        <el-form-item slot="multiSelect" label="多选操作" prop="multiSelect" v-if="table.multiSelect">
          <el-row>
            <el-col :span="8">
              <el-button size="small" type="danger" @click="tableMultiDelete" v-if="USER.auth.indexOf('deleteApp')!==-1">多选删除</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-table-column
          fixed="right"
          slot="operation"
          align="center"
          label="可用操作"
          width="100">
          <template scope="s">
            <el-tooltip placement="top">
              <div slot="content">查看应用详情</div>
              <el-button type="info" icon="search" size="mini" @click="dialogSearchOpen(s.row)"></el-button>
            </el-tooltip>
            <el-tooltip placement="top">
              <div slot="content">更多可用操作</div>
              <el-popover
                popper-class="demo-table-expand"
                placement="right"
                title="更多可用操作"
                trigger="click">
                <slot name="content">
                  <div>
                    <el-button type="info" icon="edit" size="mini" @click="tableEdit(s.row)" v-if="USER.auth.indexOf('modApp')!==-1">编辑应用</el-button>
                    <el-button type="danger" icon="delete" size="mini" @click="tableDelete(s.row)" v-if="USER.auth.indexOf('deleteApp')!==-1">删除应用</el-button>
                  </div>
                </slot>
                <el-button slot="reference" type="info" icon="more" :plain="true" size="mini"
                           class="__reference"></el-button>
              </el-popover>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-form-item label="应用名称" prop="name">
          <el-input type="text"
                    class="input"
                    v-model="autoVueTable_aName"
                    placeholder="应用名称" spellcheck="false" auto-capitalize="off" auto-complete="off"
                    auto-correct="off"></el-input>
        </el-form-item>
      </s-table>
    </el-card>

    <s-dialog :dialog="dialog" :close="dialogInit">
      <p slot="title">{{dialog.title}}<span>{{formDialog.id ? ('应用编码：' + formDialog.aCode) : ''}}</span></p>
      <s-form :form="formDialog" ref="formDialog">
        <el-row>
          <el-col :xs="24" :lg="{span: 10, offset: 0}">
            <el-form-item prop="aName" label="应用名称">
              <el-input type="text"
                        v-model="formDialog.aName"
                        placeholder="应用名称" spellcheck="false" auto-capitalize="off" auto-complete="off"
                        auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 10, offset: 2}">
            <el-form-item prop="aCode" label="应用编码" v-if="dialog.title==='新增'">
              <el-input type="text"
                        v-model="formDialog.aCode"
                        placeholder="应用编码" spellcheck="false" auto-capitalize="off" auto-complete="off"
                        auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 10, offset: 0}">
            <el-form-item prop="aLogoutUrl" label="退出地址">
              <el-input type="textarea"
                        v-model="formDialog.aLogoutUrl"
                        placeholder="退出地址" spellcheck="false" auto-capitalize="off" auto-complete="off"
                        auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 10, offset: 2}">
            <el-form-item prop="aHomeUrl" label="应用地址">
              <el-input type="textarea"
                        v-model="formDialog.aHomeUrl"
                        placeholder="应用地址" spellcheck="false" auto-capitalize="off" auto-complete="off"
                        auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </s-form>
      <el-button slot="footer" @click="dialogSave">保存</el-button>
    </s-dialog>
    <s-dialog :dialog="dialogSearch" :close="dialogSearchInit" :closeTip="false">
      <p slot="title">{{dialogSearch.title}}<span>{{'应用名称：' + dialogSearch.aName}}</span></p>
      <el-card class="box-card left">
        <el-tree
          :data="treeSearch.data"
          ref="treeSearch"
          :default-expanded-keys="['app_' + dialogSearch.id]"
          node-key="id"
          accordion
          :render-content="treeContent">
        </el-tree>
      </el-card>
      <el-button slot="footer" type="info" @click="dialogSearchSave">好</el-button>
    </s-dialog>
    <s-dialog :dialog="dialogTree" :close="dialogInit">
      <p slot="title">{{dialogTree.title}}功能项</p>
      <s-form :form="formTree" ref="formTree">
        <el-row>
          <el-col :xs="24" :lg="{span: 10, offset: 0}">
            <el-form-item prop="fName" label="功能项名称">
              <el-input type="text"
                        v-model="formTree.fName"
                        placeholder="功能项名称" spellcheck="false" auto-capitalize="off" auto-complete="off"
                        auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 10, offset: 2}">
            <el-form-item prop="fCode" label="功能项编码">
              <el-input type="text"
                        v-model="formTree.fCode"
                        placeholder="功能项编码" spellcheck="false" auto-capitalize="off" auto-complete="off"
                        auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </s-form>
      <el-button slot="footer" type="info" @click="dialogTreeSave">保存</el-button>
    </s-dialog>
  </div>
</template>

<script>
  import {AutoVue} from '~/plugins/Tools';

  function __form () {
    return {
      aName: {
        value: '',
        rule: [
          'vNull',
        ],
        notes: '应用名称',
      },
      aCode: {
        value: '',
        notes: '应用编码',
      },
      aHomeUrl: {
        value: '',
        rule: [
          'vNull',
        ],
        notes: '应用地址',
      },
      aLogoutUrl: {
        value: '',
        rule: [
          'vNull',
        ],
        notes: '退出地址',
      },
      id: {
        value: 0,
      },
    };
  }

  function __formTree () {
    return {
      appId: {value: 0, rule: [], notes: 'appId'},
      fCode: {value: '', rule: [], notes: '功能项编码'},
      fName: {value: '', rule: [], notes: '功能项名称'},
      id: {value: 0, rule: [], notes: 'id'},
      pId: {value: 0, rule: [], notes: '功能项父id'},
    };
  }

  export default AutoVue({
    transition: 'slide-fade',
    name: 'app-safety',
    store: ['DICTIONARY_custom', 'USER', 'CUSTOM'],
    data: {
      table: {
        column: [
          {
            label: '应用名称',
            prop: 'aName',
            minWidth: '120px',
            search: true,
          },
          {
            label: '应用编号',
            prop: 'aCode',
            minWidth: '120px',
            search: true,
          },
          {
            label: '应用地址',
            prop: 'aHomeUrl',
            minWidth: '300px',
          },
          {
            label: '退出地址',
            prop: 'aLogoutUrl',
            minWidth: '300px',
          },
        ],
        url: '/app/',
        key: 'id',
        tableColumn: 4,
      },
      formDialog: __form(),
      formTree: __formTree(),
      dialog: {
        title: '新增',
        formRef: 'formDialog',
      },
      dialogSearch: {
        title: '查看应用详情',
        aName: '',
        id: 0,
        row: {},
      },
      dialogTree: {
        title: '新增',
        formRef: 'formTree',
        size: 'mini',
        more: {},
        aName: '',
        id: 0,
      },
      treeSearch: {
        data: [],
      },
    },
    methods: {
      tableEdit (row) {
        this.dialogOpen('PUT', row);
      },
      tableDelete (row) {
        this.$confirm('您将删除应用。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            try {
              await this.post('/app/delete/', [row.id]);
              this.tableWatch('table');
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {
          });
      },
      tableMultiDelete () {
        this.$confirm('您将删除这些应用。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            let step = [];
            for (let item of this.table.multipleSelection) {
              step.push(item.id);
            }
            try {
              await this.post('/app/delete/', step);
              this.tableWatch('table');
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {
          });
      },

      treeContent (h, {node, data, store}) {
        let _this = this;
        return (
          <span>
            <span>
              <span>{data.fName}</span>
              <span class="fCode">{data.fCode}</span>
            </span>
            <span style="float: right; margin-right: 20px">
              <el-button size="mini" type="success" icon="edit" class={{ 'display': _this.USER.auth.indexOf('modApp') === -1 }} on-click={ event => this.treeEdit(event, store, data)}></el-button>
              <el-button size="mini" type="primary" icon="plus" class={{ 'display': _this.USER.auth.indexOf('addFunc') === -1 }} on-click={ event => this.treeAppend(event, store, data) }></el-button>
              <el-button size="mini" type="danger" icon="delete" class={{ 'display': node.level === 1 || _this.USER.auth.indexOf('deleteFun') === -1 }} on-click={ event => this.treeRemove(event, store, data) }></el-button>
            </span>
          </span>);
      },
      treeEdit (event, store, data) {
        if (typeof data.pId === 'undefined') {
          this.dialogOpen('PUT', this.dialogSearch.row);
        } else {
          this.dialogTreeOpen('PUT', {store, data});
        }
        event.stopPropagation();
      },
      treeAppend (event, store, data) {
        this.dialogTreeOpen('ADD', {store, data});
        event.stopPropagation();
      },
      treeRemove (event, store, data) {
        this.$confirm('您将删除本节点。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            try {
              await this.post('/function/delete/', [data.id]);
              store.remove(data);
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {
          });
        event.stopPropagation();
      },

      dialogInit (formRef) {
        let obj = {};
        switch (formRef) {
        case 'formDialog':
          obj = __form();
          break;
        case 'formTree':
          obj = __formTree();
          break;
        }
        this[formRef] = {
          ...this[formRef],
          ...this.ObjectClone(obj),
        };
        this.resetFields(formRef);
      },
      dialogSearchInit () {
        this.dialogSearch.aName = '';
        this.dialogSearch.id = 0;
      },
      async dialogOpen (type, more) {
        if (type) {
          type = type.toUpperCase();
        } else return;
        switch (type) {
        case 'ADD':
          this.dialog.title = '新增';
          break;
        case 'PUT':
          this.dialog.title = '修改';
          for (let index in this.formDialog) {
            if (this.formDialog.hasOwnProperty(index)) {
              if (typeof more[index] !== 'undefined') {
                this.formDialog[index] = more[index];
              }
            }
          }
          break;
        }
        this.dialog.visible = true;
      },
      dialogSearchOpen (row) {
        (async _this => {
          _this.treeSearch.data = await _this.get('/function/' + row.id);
        })(this);
        this.dialogSearch.aName = row.aName;
        this.dialogSearch.id = row.id;
        this.dialogSearch.row = row;
        this.dialogSearch.visible = true;
      },
      dialogTreeOpen (type, more) {
        if (type) {
          type = type.toUpperCase();
        } else return;
        switch (type) {
        case 'ADD':
          this.dialogTree.title = '新增';
          this.formTree.pId = isNaN(more.data.id) ? 0 : more.data.id;
          this.formTree.appId = this.dialogSearch.id;
          break;
        case 'PUT':
          this.dialogTree.title = '修改';
          for (let index in __formTree()) {
            this.formTree[index] = more.data[index];
          }
          break;
        }
        this.dialogTree.more = more;
        this.dialogTree.visible = true;
      },
      dialogSave () {
        let formRef = 'formDialog';
        if (this.dialog.title === '新增') {
          this.VALIDATE(formRef, async option => {
            try {
              let {id} = await this.post('/app/add', option);
              option.id = id;
              this.table.data = [option, ...this.table.data];
              this.table.total++;
              this.dialogInit(formRef);
              this.dialog.visible = false;
            } catch (err) {
              console.log(err);
            }
          });
        } else {
          this.VALIDATE(formRef, async option => {
            try {
              await this.post('/app/add', option);
              for (let i = 0; i < this.table.data.length; i++) {
                if (this.table.data[i].id === option.id) {
                  for (let index in this.table.data[i]) {
                    if (this.table.data[i].hasOwnProperty(index)) {
                      this.table.data[i][index] = option[index];
                    }
                  }
                }
              }
              this.dialogInit(formRef);
              this.dialog.visible = false;
            } catch (err) {
              console.log(err);
            }
          });
        }
      },
      dialogSearchSave () {
        this.dialogSearch.visible = false;
        this.dialogSearchInit();
      },
      dialogTreeSave () {
        let formRef = 'formTree';
        if (this.dialogTree.title === '新增') {
          this.VALIDATE(formRef, async option => {
            try {
              let {id} = await this.post('/function/add', option);
              option.id = id;
              let {store, data} = this.dialogTree.more;
              let pId = data.id;
              if (isNaN(pId)) { pId = 0; }
              option.pId = pId;
              store.append(option, data);
              this.dialogInit(formRef);
              this.dialogTree.visible = false;
            } catch (err) {
              console.log(err);
            }
          });
        } else {
          this.VALIDATE(formRef, async option => {
            option.appId = this.dialogSearch.id;
            try {
              await this.post('/function/add', option);
              let {data} = this.dialogTree.more;
              let pId = data.id;
              if (isNaN(pId)) { pId = 0; }
              option.pId = pId;
              for (let index in __formTree()) {
                this.dialogTree.more.data[index] = option[index];
              }
              this.dialogInit(formRef);
              this.dialogTree.visible = false;
            } catch (err) {
              console.log(err);
            }
          });
        }
      },
    },
    mounted: function () {
      this.tableWatch('table');
    },
  });
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
  .app {
    .fCode{
      margin-left: 5px;
      color: #42b983;
      font-size: 12px;
    }
  }
</style>

<style scoped lang="scss">
  .box-card {
    margin: 20px;
  }

  .createTimeSpan {
    display: block;
    margin-top: 34px;
  }

  @media screen and (max-width: 800px) {
    .createTimeSpan {
      margin-top: 0;
    }
    .box-card {
      margin: 0;
    }
  }

  .el-select {
    width: 100%;
  }
</style>
